<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图层层级操作</title>
  <style>
    .btn-x {
      margin-bottom: 10px;
    }
    #canvasBox {
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <div class="btn-x">
    <button onclick="bringToFront()">矩形移到顶层</button>
    <button onclick="sendToBack()">矩形移到底层层</button>
    <button onclick="bringForward()">三角形往上走一层</button>
    <button onclick="sendBackwards()">圆形往下走一层</button>
    <button onclick="moveTo()">将三角形移到0层</button>
  </div>
  <canvas id="canvasBox" width="600" height="600"></canvas>

<script src="../../script/fabric.js"></script>
<script>
  let canvas = null
  let rect = null
  let circle = null
  let triangle = null

  window.onload = () => {
    canvas = new fabric.Canvas('canvasBox')

    rect = new fabric.Rect({
      top: 30,
      left: 30,
      fill: 'orange',
      width: 100,
      height: 100
    })

    circle = new fabric.Circle({
      top: 50,
      left: 60,
      fill: 'hotpink',
      radius: 50
    })

    triangle = new fabric.Triangle({
      top: 80,
      left: 30,
      width: 80,
      height: 100,
      fill: 'blue'
    })

    canvas.add(rect, circle, triangle)
  }

  // 矩形移到顶层
  function bringToFront() {
    // 方法1
    canvas.bringToFront(rect)

    // 方法2
    // rect.bringToFront()
  }

  // 矩形移到底层层
  function sendToBack() {
    // 方法1
    canvas.sendToBack(rect)

    // 方法2
    // rect.sendToBack()
  }

  // 三角形往上走一层
  function bringForward() {
    // 方法1
    canvas.bringForward(triangle)

    // 方法2
    // triangle.bringForward()
  }

  // 圆形往下走一层
  function sendBackwards() {
    // 方法1
    canvas.sendBackwards(circle)

    // 方法2
    // circle.sendBackwards()
  }

  // 三角形移到0层
  function moveTo() {
    // 方法1
    // canvas.moveTo(triangle, 0)

    // 方法2
    triangle.moveTo(0)
  }
</script>
</body>
</html>